package com.eshore.norm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.eshore.norm.mapper.NormAddressGroupMapper;
import com.eshore.norm.pojo.constant.Const;
import com.eshore.norm.pojo.dto.NormAddressGroup;
import com.eshore.norm.pojo.po.NormAddressGroupPO;
import com.eshore.norm.service.INormAddressGroupService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eshore.norm.util.DateUtils;
import com.eshore.norm.util.ListStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 安全组列表 服务实现类
 * </p>
 *
 * @author chenjl
 * @since 2024-01-05
 */
@Service
public class NormAddressGroupServiceImpl extends ServiceImpl<NormAddressGroupMapper, NormAddressGroup> implements INormAddressGroupService {

    @Override
    public void dataImport(NormAddressGroupPO po) {
        Optional<NormAddressGroupPO> po_optional = Optional.ofNullable(po);
        po_optional.ifPresent(s -> {
            Optional<List<NormAddressGroupPO.AddressGroupsDTO>> dto_optional = Optional.ofNullable(s.getAddressGroups());
            dto_optional.ifPresent(item -> {
                List<String> newGroupIds = item.stream().map(NormAddressGroupPO.AddressGroupsDTO::getId).collect(Collectors.toList());
                cleanOldData(Const.CONFIG_ID, newGroupIds);
                //将po转化成实体对象入库
                List<NormAddressGroup> entityList = toAddressGroup(Const.CONFIG_ID, dto_optional);
                if (!CollectionUtils.isEmpty(entityList)) {
                    getBaseMapper().insertOrUpdateBatch(entityList);
                }
            });
        });
    }

    /**
     * 删除现已不存在的数据，保持同步一致
     *
     * @param configId
     * @param newGroupIds 需要同步的索引Id集合
     * @author v-chenjl62
     * @date 2024/1/10
     */
    private void cleanOldData(Long configId, List<String> newGroupIds) {
        List<String> oldGroupIds = lambdaQuery().eq(NormAddressGroup::getConfigId, configId).list().stream().map(NormAddressGroup::getGroupId).collect(Collectors.toList());
        //筛选出差异的xxxId即为多余的需要删除
        oldGroupIds.removeAll(newGroupIds);
        if(!CollectionUtils.isEmpty(oldGroupIds)) {
            getBaseMapper().delete(new QueryWrapper<NormAddressGroup>().in("group_id", oldGroupIds));
        }
    }

    private List<NormAddressGroup> toAddressGroup(Long configId, Optional<List<NormAddressGroupPO.AddressGroupsDTO>> list_optional) {
        return list_optional.get().stream().map(item -> {
            NormAddressGroup entity = new NormAddressGroup();
            BeanUtils.copyProperties(item,entity , "id","addresses","sysTags","tags");
            entity.setGroupId(item.getId());//xxxId 是唯一索引
            entity.setAddresses(ListStringUtils.listToString(item.getAddresses()));
            entity.setSysTags(ListStringUtils.listToString(item.getSysTags()));
            entity.setTags(ListStringUtils.listToString(item.getTags()));
            entity.setId(IdWorker.getId());
            entity.setConfigId(configId);
            entity.setCreateDate(DateUtils.parse(item.getCreatedAt(),DateUtils.DATE_TIME_T_PATTERN));
            entity.setUpdateDate(DateUtils.parse(item.getUpdatedAt(),DateUtils.DATE_TIME_T_PATTERN));
            return entity;
        }).collect(Collectors.toList());
    }

    @Override
    public String getGroupIdByName(String sgName, String tenantId) {
        return lambdaQuery()
                .eq(NormAddressGroup::getName,sgName)
                .eq(NormAddressGroup::getTenantId,tenantId)
                .one()
                .getGroupId();
    }
}
